const express = require('express');
const multer = require('multer');
const path = require('path');
const multiparty = require('multiparty');
var router = express.Router();
// const db = require("../utils/dbconfig")

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, 'public/images') // 设置上传文件保存的目录，不存在会自动创建
  },
  filename: function (req, file, cb) {
    cb(null, Date.now() + (path.extname(file.originalname) || '.jpg')) // 更改文件名为时间戳加扩展名
  }
});
const upload = multer({ storage: storage });
router.post('/', upload.single('file'), function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");

  if (!req.file) {
    return res.status(400).send('No file uploaded.');
  }
  console.log(req.file, req.body)
  // 文件已成功上传
  res.json({
    message: '成功接收照片',
    fileName: req.file.filename,
    filePath: `/images/${req.file.filename}`
  });






});
// router.post('/', function (req, res, next) {
//   var form = new multiparty.Form();
//   form.uploadDir = './public/images'; //上传图片保存的地址 目录必须存在 还需要注意配置静态文件托管
//   form.parse(req, function (err, fields, files) {
//     //获取提交的数据以及图片上传成功返回的图片信息
//     console.log(fields);//获取表单的数据
//     console.log(files);//图片上传成功返回的信息
//     res.writeHead(200, { 'content-type': 'text/plain' });
//     res.write('received upload:\n\n');
//   });

// });

module.exports = router;
